package org.mogu;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.mogu.control.model.IMUser;
import org.mogu.db.DBhelper;
import org.mogu.service.InfoSync;
import org.mogu.staticvalue.Convert;
import org.mogu.tools.CityData;
import org.mogu.tools.HeaderPic;

import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class QQ_Search_List extends ListActivity {
	private String result;
	private String code;
	private String maincode;
	private ListView list;
	private TextView message;
	public  QQ_Search_List instance = null;
	CityData cityData=new CityData();
	Intent intent;
	private List<IMUser> resultImUser=new ArrayList<IMUser>();
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.qq_search_list);
		instance=this;
		list=getListView();
		message=(TextView)findViewById(R.id.nomessage);
		intent=this.getIntent();  
		Bundle bunde = intent.getExtras();
		result = bunde.getString("result");
		maincode = bunde.getString("maincode");
		code = bunde.getString("code");
		String c="-";
		try {
			JSONArray imusers=new JSONArray(result);
			IMUser imuser;
			JSONObject user;
			for(int i=0;i<imusers.length();i++){
				user=imusers.getJSONObject(i);
				imuser=new IMUser();
				imuser.setUname(user.getString("username"));
				imuser.setMaincode(maincode);
				imuser.setCode(code+c+imuser.getUname());
				imuser.setUnicename(user.getString("nickname"));
				imuser.setBirthday(user.getString("birthday"));
				imuser.setSheng(user.getString("sheng"));
				imuser.setCity(user.getString("city"));
				imuser.setSex(user.getString("sex"));
				if(user.has("desc")){
					imuser.setDesc(user.getString("desc"));
				}
				if(user.has("header")){
					imuser.setHeader(user.getInt("header"));
				}
				
				resultImUser.add(imuser);
			}
			
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			
		}
		setListAdapter(new QQSearchAdapter());
		if(resultImUser.size()==0){
			list.setVisibility(View.GONE);
			message.setVisibility(View.VISIBLE);
		}else{
			list.setVisibility(View.VISIBLE);
			message.setVisibility(View.GONE);
		}
		
	}
	
	public void onBack(View view) {
    	if(intent==null){
    		return;
    	}
    	this.setResult(RESULT_OK, intent);
    	this.finish(); 
    }
	
	public void onListItemClick(ListView parent, View v, int position, long id) {
		
		
		IMUser imUser=resultImUser.get(position);
		String[] arr={Convert.uname,imUser.getCode()};
		synchronized (InfoSync.class) {
			Cursor userCursor = DBhelper.getDBHelper(this).getReadableDatabase()
					.rawQuery(
							"select code,title,content,replyType,maincode,level,father,lastUpdateTime,id from content where username=? and code=?",
							arr);
			userCursor.moveToFirst();
			while(!userCursor.isAfterLast()){
				imUser.setCode(userCursor.getString(0));
				 imUser.setTitle(userCursor.getString(1));
				 imUser.setContent(userCursor.getString(2));
				 imUser.setReplyType(userCursor.getString(3));
				 imUser.setMaincode(userCursor.getString(4));
				 imUser.setLevel(userCursor.getString(5));
				 imUser.setFather(userCursor.getString(6));
				 imUser.setLastUpdateTime(userCursor.getString(7));
				 imUser.setId(userCursor.getInt(8));
				 userCursor.moveToNext();
			}
			userCursor.close();

		}
		
		Intent mIntent = new Intent(this, ContactManagerActivity.class);
		Bundle bundle = new Bundle();
		bundle.putSerializable("iMUser", imUser);
		mIntent.putExtras(bundle);
//		mIntent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
		startActivityForResult(mIntent,0);
//		JSONObject user=new JSONObject();
//		try {
//			user.put("username", imuser.getUname());
//			user.put("nickname", imuser.getUnicename());
//			user.put("birthday", imuser.getBirthday());
//			user.put("sheng", imuser.getSheng());
//			user.put("city", imuser.getCity());
//			user.put("sex", imuser.getSex());
//			if(imuser.getDesc()!=null){
//				user.put("desc",imuser.getDesc() );
//			}
//		} catch (JSONException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//		ContentValues activeuser = new ContentValues();
//		activeuser.put("maincode", imuser.getMaincode());
//		activeuser.put("content", user.toString());
//		
//		activeuser.put("status", "1");
//		activeuser.put("level", "101");
//		activeuser.put("father", imuser.getMaincode()+"-s1");
//		activeuser.put("replyType", "30");
//		activeuser.put("lastUpdateTime", Convert.format1.format(new Date()));
//		String[] where={imuser.getCode(),Convert.uname};
//		synchronized (InfoSync.class) {
//			int num=DBhelper.getDBHelper(this).getWritableDatabase().update("content", activeuser, "code=? and username=?", where);
//			if(num==0){
//				activeuser.put("code",imuser.getCode() );
//				activeuser.put("username", Convert.uname);
//				activeuser.put("title", "2");
//				imuser.setTitle("2");
//				DBhelper.getDBHelper(this).getWritableDatabase().insert("content", null, activeuser);
//			}
//			
//		}
//		
//		
//		Intent mIntent = new Intent(this, ChatWindowsActivity.class);
//    	Bundle bundle = new Bundle();
//		bundle.putSerializable("iMUser", imuser);
//		mIntent.putExtras(bundle);
//    	startActivityForResult(mIntent, 0);
	}
	
	class QQSearchAdapter extends ArrayAdapter {
		QQSearchAdapter() {
			super(instance, R.layout.recent_list_item, resultImUser);
		}

		/*
		 * 列表项的视图函数
		 * */
		public View getView(int paramInt, View paramView, ViewGroup paramViewGroup){
			System.out.println("getView");
			
			View localView = paramView;
			if (localView == null) {
				LayoutInflater inflater = getLayoutInflater();
				localView = inflater
						.inflate(R.layout.qq_search_list_item, paramViewGroup, false);
			}
			//判断当前view视图参数是否为null
		    /*
		     * 相关控件设置
		     * */
		    //头像
		    ImageView headIcon = (ImageView)localView.findViewById(R.id.recent_headIcon);
		    //在线标识
//		    ImageView buddyStatue = (ImageView)localView.findViewById(R.id.recent_buddyStatue);
		    //昵称
		    TextView name = (TextView)localView.findViewById(R.id.recent_name);
		    //心情
		    TextView info = (TextView)localView.findViewById(R.id.recent_info);
		    TextView desc = (TextView)localView.findViewById(R.id.recent_desc);
//		    //编辑按钮
//		    ImageView contextbtn = (ImageView)localView.findViewById(R.id.recent_contextbtn);
//		    //设置编辑按钮的单击事件监听器
//		    contextbtn.setOnClickListener(this);
		    
		    
		    /*
		     * 设置控件内容
		     * */
//	    	TreeNode childItem = (TreeNode)recentContactV.get(paramInt);
	    	IMUser imUser=resultImUser.get(paramInt);
		    name.setText(imUser.getUnicename());
		    desc.setText(imUser.getDesc());
		    String sex="true".equals(imUser.getSex())?" 性别：女 ":" 性别：男 ";
		    Date birthday;
			try {
				birthday = Convert.format1.parse(imUser.getBirthday().subSequence(0, 19).toString());
			} catch (Exception e) {
				// TODO Auto-generated catch block
				birthday=new Date();
				birthday.setYear(birthday.getYear()-18);
			}
		    info.setText(" 年龄: "+(new Date().getYear()-birthday.getYear())+" 岁 ");
		    info.append(sex);
		    if(imUser.getSheng()!=null&&"".equals(imUser.getSheng())){
		    	info.append(" "+cityData.sheng[Integer.valueOf(imUser.getSheng())-1]);
		    	if(imUser.getCity()!=null&&"".equals(imUser.getCity())){
			    	info.append(" - "+cityData.city.get(cityData.sheng[Integer.valueOf(imUser.getSheng())-1])[Integer.valueOf(imUser.getCity())-1]);
			    }
		    }
		    headIcon.setImageResource(HeaderPic.getHeader(imUser.getHeader()));
		    
		    //设置视图间距
		    localView.setPadding(0, 0, 0, 0);
		    //获取资源文件对象
		    Drawable localDrawable = instance.getResources().getDrawable(R.drawable.highlight_item);
		    //设置视图背景
		    localView.setBackgroundDrawable(localDrawable);
		    
		    
		    return localView;
		}
	}
}
